package com.woan.api.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.ResourceBundle;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.oreilly.servlet.MultipartRequest;
import com.woan.api.model.SysPhoto;
import com.woan.api.services.PhotoClientServices;
import com.woan.api.services.UserClientServices;
import com.woan.api.util.CommonUtil;
import com.woan.api.util.CopyFile;
import com.woan.api.util.FuncDate;
import com.woan.api.util.HttpTool;
import com.woan.api.util.Randoms;
import com.woan.api.util.ScaleImage;
import com.woan.api.vo.Json;


public class Addphoto extends HttpServlet {
	HttpTool ht = new HttpTool();
	public Addphoto() {
		super();
	}
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String oldPath = this.getServletContext().getRealPath("/")+"photos";// 上传的文件保存到服务器的地址
		int maxPostSize = 5000 * 1024 * 1024;
		System.out.println("--------------图片上传----------------");
		ResourceBundle rb_config = ResourceBundle.getBundle("config");
		MultipartRequest multi = null;
		try {
			multi = new MultipartRequest(request, oldPath, maxPostSize,"UTF-8");
			Enumeration filesname = multi.getFileNames();//文件
			String groupname = multi.getParameter("fristname");
			String username = multi.getParameter("userName");
			String userpwd = multi.getParameter("passwd");
			String devicenum = multi.getParameter("deviceNum");
			String filelength = multi.getParameter("fileLength");
			if(filelength == null || filelength.equals(""))
				filelength="0";
			ServletContext servletContext = this.getServletContext();     
	        WebApplicationContext wac = null;     
	        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);    
	        PhotoClientServices photoClientServices = (PhotoClientServices) wac.getBean("photoClientServices");
	        UserClientServices userClientServices = (UserClientServices) wac.getBean("userClientServices");
	        Json objson = new Json();
	        objson = userClientServices.loginInfo(groupname, username,userpwd,devicenum);
			String json = "";
			if("0".equals(objson.getResults())){
				System.out.println("上传开始————————————————————————————————");
				String filename = "";//文件名
				String name1 = (String) filesname.nextElement();
				filename = multi.getFilesystemName(name1);//获取上传文件的名称
				String newFileName = CommonUtil.RandomStrNumDate(4)+filename.substring(filename.lastIndexOf("."));//新的文件名
				String newPath = oldPath+"/"+objson.getAdmin().getUid();//文件保存目录
				File oldFile = new File(oldPath);
				if(!oldFile.exists()){//判断文件夹是否存在，不存在创建
					oldFile.mkdir();
				}
				File newFile = new File(newPath);
				if(!newFile.exists()){//判断文件夹是否存在，不存在创建
					newFile.mkdir();
				}
				File file2 = new File(newPath);
				if(!file2.exists()){//判断文件夹是否存在，不存在创建
					file2.mkdir();
				}
					
				CopyFile.CopyFile(oldPath+"/"+filename, newPath, newFileName);//复制文件
				CopyFile.doFolder(oldPath+"/"+filename);//删除原来文件
				System.out.println("上传成功————————————————————————————————");
				File picture = new File(newPath+"/"+newFileName); 
		        System.out.println(picture.length());
		        System.out.println("获取文件大小————————————————————————————————");
		        if(Long.parseLong(filelength)==picture.length())
		        {
		        	//生成缩略图
					String imgdist = newPath;
					String imgsrc = newPath+"/"+newFileName;
					imgdist = imgdist+"/"+"thumbnail_"+newFileName;
					String serverinfo=rb_config.getString("serverinfo");
					int widthdist  = Integer.parseInt(rb_config.getString("thumbnail_width"));
					int heightdist = Integer.parseInt(rb_config.getString("thumbnail_height"));

					ScaleImage.saveImageAsJpg(imgsrc,imgdist,widthdist,heightdist);
					System.out.println("缩略图成功————————————————————————————————");
					// 插入数据
			
					SysPhoto photo = new SysPhoto();
					FuncDate fd = new FuncDate();
					photo.setRid(objson.getAdmin().getSysRole().getRid());
					photo.setPid(fd.FindCurSysTime()+Randoms.getRandomString(3));
					photo.setUid(objson.getAdmin().getUid());
					photo.setUrl("/photos/"+objson.getAdmin().getUid()+"/"+newFileName);
					photo.setSmurl("/photos/"+objson.getAdmin().getUid()+"/thumbnail_"+newFileName);
					//photo.setLatitude(latitude);
					//photo.setLongitude(longitude);
					//photo.setCountrycode(countrycode);
					//photo.setCountryname(countryname);
					//photo.setProvince(province);
					//photo.setCity(city);
					//photo.setCounties(counties);
					photo.setCreattime(fd.getSysTime());
					photo.setIsdel("1");
					String res = photoClientServices.save(photo);
					System.out.println("插入数据完成————————————————————————————————"+res);
					if("0".equals(res)){
						json = "{\"results\":0,\"items\":\"\",\"errMsg\":\"成功\"}";
					}else{
						json = "{\"results\":1,\"items\":\"\",\"errMsg\":\"失败\"}";
					}
		        }
		        else
		        {
		        	json = "{\"results\":1,\"items\":\"\",\"errMsg\":\"失败\"}";
		        }
				// 返回结果
				ht.retData(response, json);
			}
			else
			{
				json = "{\"results\":\""+objson.getResults()+"\",\"items\":\"\",\"errMsg\":"+objson.getErrMsg()+"}";
				System.out.println("鉴权未通过 json = "+json);
				ht.retData(response,json);
			}	
		} catch (Exception e) {
			System.out.println("e = "+e);
			ht.retData(response, "{\"result\":2}");
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
